package com.sgb.kjwl.view.ui.activity.self.shop;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityShopInfoBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.pick.PickCompanyDetailFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopMachineChildFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopMaterialChildFragment;
import com.sgb.kjwl.view.ui.fragment.shop.ShopTdChildFragment;
import com.sgb.kjwl.viewmodel.self.ShopInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
//由WebsiteInfoActivity替代
@Deprecated
public class ShopInfoActivity extends AppActivity {
    private ActivityShopInfoBinding binding;
    boolean userFocusCompanyStatus;
    @Inject
    ShopInfoModel viewModel;
    private String[] name = new String[]{"商品", "租赁经营", "招采经营", "集采/团购", "工队"};
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private String shopId;
    private String companyNo;
    private int mInitPosition;
    private int childPosition;

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, ShopInfoActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String id, int position) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("position", position);
        intent.setClass(context, ShopInfoActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String id, String companyNo, int position, int childPosition) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("companyNo", companyNo);
        intent.putExtra("position", position);
        intent.putExtra("childPosition", childPosition);
        intent.setClass(context, ShopInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    @Override
    protected void initView() {
        shopId = getIntent().getStringExtra("id");
        companyNo = getIntent().getStringExtra("companyNo");
        mInitPosition = getIntent().getIntExtra("position", 0);
        childPosition = getIntent().getIntExtra("childPosition", 0);
        binding = DataBindingUtil.setContentView(ShopInfoActivity.this, R.layout.activity_shop_info);
        binding.setViewModel(viewModel);
        binding.include.ivBack.setOnClickListener(this);
        binding.shopMessage.setOnClickListener(this);
        binding.include.titleView.setText(getString(R.string.shop_businesses));
    }

    @Override
    protected void init() {
        SharedPreferenceUtil.init(this);
        Map<String,Object> map = new HashMap<>();
        map.put("id", companyNo);
        viewModel.shopDetail(map);
        viewModel.getShopImInfo(shopId);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_attention:
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    MToast.showToast(this, "您还没有登录，请先登录");
                    return;
                }
                viewModel.userFocusCompany(shopId);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.shop_info_layout:
                ShopCompanyInfoActivity.start(this, viewModel.shopInfoEntity.get());
                break;
            case R.id.shop_message:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    IMUtils.getInstance().buildSingleTalking(viewModel.shopImAccount.get());
//                    MToast.showToast(this, "敬请期待...");
//                    NimUIKit.startP2PSession(ShopInfoActivity.this, viewModel.shopImAccount.get());
                }
                break;
            case R.id.shop_des:
                MToast.showToast(this, "敬请期待...");
                break;
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(ShopInfoActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(this, EventConstant.EVENT_SHOP_INFO_ACTIVITY_JUMP);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code != 1000) {
                VerificationCodeLoginActivity.start(ShopInfoActivity.this, EventConstant.EVENT_SHOP_INFO_ACTIVITY_JUMP);
            }
        }, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code == 1000) {
                OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                oneKeyLoginEntity.setPlateform("Android");
                viewModel.oneKeyLogin(oneKeyLoginEntity);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void setData() {
        if (viewModel.shopInfoEntity.get().getAuthTime() != null) {
            binding.tvShopTime.setText(String.format("入驻日期：%s", DateUtils.stampToDay(viewModel.shopInfoEntity.get().getAuthTime())));
        }
        RoundedCorners roundedCorners = new RoundedCorners(4);
//通过RequestOptions扩展功能,override采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = new RequestOptions().bitmapTransform(roundedCorners).override(300, 300)
                .placeholder(R.drawable.null_img_list)//图片加载出来前，显示的图片
                .error(R.drawable.shop_default);//图片加载失败后，显示的图片
        Glide.with(this).load(viewModel.shopInfoEntity.get().getLogo()).apply(options)//异常时候显示的图片
                .into((binding.ivShopDefault));
        ArrayList<Fragment> mFragments = new ArrayList<>();
        mFragments.add(ShopMaterialChildFragment.newInstance(shopId));
        mFragments.add(ShopMachineChildFragment.newInstance(companyNo,"", childPosition));//租赁经营
        mFragments.add(PickCompanyDetailFragment.newInstance(viewModel.shopInfoEntity.get().getCompanyNo()));
//        mFragments.add(ShopJcChildFragment.newInstance(shopId));
        mFragments.add(ShopTdChildFragment.newInstance(shopId));
        SlidingFragmentPagerAdapter mAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, name);
        binding.viewpager.setAdapter(mAdapter);
        binding.viewpager.setOffscreenPageLimit(3);
        binding.tablayout.setupWithViewPager(binding.viewpager);
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        binding.viewpager.setCurrentItem(mInitPosition);
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_SHOP_INFO_ACTIVITY_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void setuserFocusCompanyStatus() {
        setuserFocusCompanyStatus(!userFocusCompanyStatus);
    }

    public void setuserFocusCompanyStatus(boolean data) {
        userFocusCompanyStatus = data;
    }
}
